package imu.ming.spring.aspect;


import imu.ming.spring.LogEntity;

import imu.ming.spring.annotation.SystemLog;
import imu.ming.spring.service.SystemLogService;
import imu.ming.spring.utils.IpUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;


@Aspect
@Component
public class SystemLogAspect {

    @Autowired
    private SystemLogService systemLogService;

    @Pointcut(value = "@annotation(imu.ming.spring.annotation.SystemLog)")
    public void pointcut(){

    }

    /**
     * 方法成功执行后新增日志
     *
     * @param joinPoint
     */
    @AfterReturning(pointcut = "pointcut()")
    public void afterReturning(JoinPoint joinPoint){
        System.out.println("afterReturning;");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        SystemLog logAnnotation = method.getAnnotation(SystemLog.class);

        LogEntity log = new LogEntity();
        log.setCreateTime(new Date(System.currentTimeMillis()));
        log.setIp(IpUtil.getIpAddr(request));
        log.setModuleName(logAnnotation.module());
        log.setContent(logAnnotation.content());
        if (logAnnotation.content().equals("用户登录")){
            log.setUserName(request.getParameter("id"));
            log.setResult((String) request.getAttribute("msg"));
        }
        System.out.println("systemLogService.insertLog(log);");
        systemLogService.insertLog(log);
    }
}
